package acp

import (
	"barge/pkg/manager"
	"fmt"
)

func (c *Controller) GetRegistryInfo() (*manager.Registry, error) {
	globalInfoUrl := c.Host + getGlobalInfoUrlPath(c.Option.Cluster)
	cm := new(ConfigMap)
	_, err := c.R().
		SetAuthToken(c.Option.Token).
		SetResult(cm).
		Get(globalInfoUrl)
	if err != nil {
		return nil, err
	}
	address := cm.Data["registryAddress"]

	registryUrl := c.Host + getRegistryUrlPath(c.Option.Cluster)
	secret := new(Secret)
	_, err = c.R().
		SetAuthToken(c.Option.Token).
		SetResult(secret).
		Get(registryUrl)
	if err != nil {
		return nil, err
	}
	username := secret.GetByKey("username")
	password := secret.GetByKey("password")
	registry := &manager.Registry{
		Address:  address,
		Username: username,
		Password: manager.Password{
			Raw: password,
		},
	}
	return registry, nil
}

func getGlobalInfoUrlPath(cluster string) string {
	return fmt.Sprintf("/kubernetes/%s/api/v1/namespaces/kube-public/configmaps/global-info", cluster)
}

func getRegistryUrlPath(cluster string) string {
	return fmt.Sprintf("/kubernetes/%s/api/v1/namespaces/cpaas-system/secrets/registry-admin", cluster)
}
